package mobi.hami.huapin.task;

import com.alibaba.druid.sql.visitor.functions.Now;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import io.swagger.util.Json;
import mobi.hami.huapin.controller.TestController;
import mobi.hami.huapin.core.stock.StockUtil;
import mobi.hami.huapin.dto.SKUPresentDTO;
import mobi.hami.huapin.dto.UserOrderDTO;
import mobi.hami.huapin.model.*;
import mobi.hami.huapin.service.*;
import mobi.hami.huapin.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 定时任务
 * Create by 小峰 on 2018/9/3.
 */
@Component
public class HuaPinTask {

    private static final Logger logger = LoggerFactory.getLogger(TestController.class);
    @Autowired
    private UserOrderService userOrderService;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private UserWechatService userWechatService;
    @Autowired
    private HuaPinService huaPinService;

    @Autowired
    private SubjectService subjectService;
    @Autowired
    private UserPresentSkuService userPresentSkuService;
    @Autowired
    private HauPinTaskService hauPinTaskService;
    @Autowired
    private UserOrderDetailService userOrderDetailService;

    @Value("${huapin.failedUrl}")
    private String failedUrl;

    @Value("${huapin.failedNoteUrl}")
    private String failedNoteUrl;
    @Value("${task.isInvoke}")
    private Boolean isInvoke;

    /**
     * 拼团结束处理
     */
    //@Scheduled(cron = "0/5 * * * * ? ") //间隔5秒执行
    @Scheduled(cron = "0 0 16 * * ?") //每天16点执行
    public void collageEndTask() {
        if(!isInvoke){
            return;
        }
        StockUtil stockUtil= new StockUtil();
        List<HuaPin> huaPinList = huaPinService.getCurrentDayHuaPinList();
        List<SKUPresentDTO> skuPreSentList = subjectService.getSKUPreSentListBySubjectId(10);
        for (HuaPin huaPin : huaPinList) {
            List<UserOrderDTO> userOrderDTOList = userOrderService.getListByHuapnId(huaPin.getId());
//            if (userOrderDTOList.size() < 3)
            if (3 > userOrderDTOList.stream().mapToInt(UserOrder::getSku_count).sum()) {
                huapinFail(userOrderDTOList, huaPin);
            } else {
                huapinSucceed(skuPreSentList, userOrderDTOList, huaPin);
            }
        }

        //未付款成功的,返回库存处理
        List<UserOrderDTO> unPaylist=userOrderService.getYesterdayUnPayList();
        if(unPaylist !=null && unPaylist.size()>0){
            for(UserOrderDTO model:unPaylist){
                //实际库存返还
                stockUtil.actualRepertoryByOrderCode(model.getOrder_code(),"wms/stock/actualReturnRepertory.do");
            }
        }

    }


    @Scheduled(cron = "0 0 0/2 * * ?") //每2个小时执行一次
    public void sendStatusTask() {
        userOrderService.taskUpdateSendStatus();
    }


    // @Scheduled(cron = "0/5 * * * * ? ")
    public void yunZhanTest() {
        StockUtil stockUtil = new StockUtil();
        // addRepertoryBySkuInfo("yztest",116,1);
        stockUtil.actualRepertoryByOrderCode("yztest","wms/stock/actualSubRepertory.do");
        // https://hmall228.hami.mobi/wms/wms/stock/actualReturnRepertory.do
        // https://hmall228.hami.mobi/wms/wms/stock/actualSubRepertory.do


       /* Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Accept", "application/json");

        try {
            String response = HttpUtil.post(failedNoteUrl,
                    JSONUtils.toJSONString(jointFailedNoteInfo("oIto65GWtRzbP3YxbhJT2TtPYoeY", 10)),
                    headers);
            System.out.println("调用退款通知结果" + response);

        } catch (Exception ex) {
            logger.error("调用退款通知接口出现异常：" + ex.getMessage());
        }*/
    }


    /**
     * 拼团失败
     */
    private void huapinFail(List<UserOrderDTO> userOrderDTOList, HuaPin huaPin) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Accept", "application/json");
        StockUtil stockUtil= new StockUtil();
        for (UserOrder userOrder : userOrderDTOList) {
            UserWechat userWechat = userWechatService.findModelbyUserId(userOrder.getUser_id());
            if (userWechat == null) {
                userWechat = new UserWechat();
                userWechat.setWechat_small_id("122312312312");
            }
            Map<String, String> map = new HashMap<String, String>();
            map.put("orderid", userOrder.getOrder_code());
            map.put("openid", userWechat.getWechat_small_id());
            map.put("userid", userOrder.getUser_id().toString());
            map.put("paymoney", userOrder.getPay_money().toString());
            map.put("paymodel", userOrder.getPay_model().toString());
            String response = null;
            try {
                response = HttpUtil.post(failedUrl, JSONUtils.toJSONString(map), headers);

            } catch (Exception ex) {
                logger.error("调用退款接口出现异常：" + ex.getMessage());
            }

            boolean values = (Boolean) JSON.parseObject(response, map.getClass()).get("success");
            if (values) {
                logger.info("[退款接口成功],订单号为:" + userOrder.getOrder_code());
            } else {
                logger.error("调用退款接口出现失败,订单编号为:" + userOrder.getOrder_code());
                continue;
            }
            userOrder.setOrder_status(3);
            userOrder.setUpdate_time(new Date());
            userOrderService.updateOrderByPrimaryKeySelective(userOrder);
            //退优惠券
            if (userOrder.getCoupon_id() != null && userOrder.getCoupon_id() > 0) {
                UserCoupon userCoupon = new UserCoupon();
                userCoupon.setId(userOrder.getCoupon_id());
                userCoupon.setIs_valid(3);
                userCouponService.update(userCoupon);
            }

            if (userWechat.getId() != null && userWechat.getId() > 0) {
                //更新拼团次数UserWechat
                if (huaPin.getUser_id().equals(userOrder.getUser_id())) {
                    //团长
                    userWechat.setLaunch_collage_count(userWechat.getLaunch_collage_count() - 1);
                } else {
                    userWechat.setPartack_collage_count(userWechat.getPartack_collage_count() - 1);
                }
                userWechatService.update(userWechat);
            }

            try {
                response = HttpUtil.post(failedNoteUrl,
                        JSONUtils.toJSONString(jointFailedNoteInfo(userWechat.getWechat_small_id(), userOrder.getPay_money())),
                        headers);
                logger.info("调用退款通知结果" + response);

            } catch (Exception ex) {
                logger.error("调用退款通知接口出现异常：" + ex.getMessage());
            }
            //实际库存返还
            stockUtil.actualRepertoryByOrderCode(userOrder.getOrder_code(),"wms/stock/actualReturnRepertory.do");
        }
        huaPin.setStatus(3);
        huaPinService.update(huaPin);
    }

    /**
     * 拼团成功
     *
     * @param skuPreSentList   赠送商品列表
     * @param userOrderDTOList
     * @param huaPin
     */
    private void huapinSucceed(List<SKUPresentDTO> skuPreSentList, List<UserOrderDTO> userOrderDTOList, HuaPin huaPin) {

        List<Integer> huapinSkuId = new ArrayList<>();
        StockUtil stockUtil= new StockUtil();
        Boolean isSendsku;
        for (UserOrder userOrder : userOrderDTOList) {
            List<UserPresentSku> presentCountList = userPresentSkuService.getUserPresentCount(userOrder.getUser_id());
            if (presentCountList == null) {
                presentCountList = new ArrayList<>();
                isSendsku = false;
            } else {
                isSendsku = userPresentSkuService.getCountByUserAndHuapin(huaPin.getId(), userOrder.getUser_id());
            }
            if(!isSendsku){
                SKUPresentDTO skuPresentDTO = hauPinTaskService.calculatePresentSKU(skuPreSentList, presentCountList, huapinSkuId);
                huapinSkuId.add(skuPresentDTO.getId());
                userOrderDetailService.instanceUserOrderDetail(skuPresentDTO, userOrder.getId(),userOrder.getOrder_code());
                userPresentSkuService.saveUserPresentSkuByModel(userOrder.getUser_id(), huaPin.getId(), userOrder.getId(), skuPresentDTO.getId());
             }
            userOrder.setOrder_status(4);
            userOrder.setUpdate_time(new Date());
            userOrderService.updateOrderByPrimaryKeySelective(userOrder);
            //实际扣减库存
            stockUtil.actualRepertoryByOrderCode(userOrder.getOrder_code(),"wms/stock/actualSubRepertory.do");
        }
        huaPin.setStatus(2);
        huaPinService.update(huaPin);
    }


    /**
     * 拼接退款通知内容
     *
     * @return
     */
    private Map<String, Object> jointFailedNoteInfo(String openId, Object money) {
        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("touser", openId);
        reqMap.put("template_id", "hm3vn-na8Xld-yZN1bV-oEt_RF3aNnt4j_mxcJLRUhk");
        reqMap.put("page", "/pages/onehome/onehome");
        reqMap.put("form_id", null);
        reqMap.put("emphasis_keyword", null);
        reqMap.put("color", null);

        HashMap<String, Map<String, Object>> data = new HashMap<String, Map<String, Object>>();
        Map<String, Object> keyword1 = new HashMap<String, Object>();
        keyword1.put("value", money);
        data.put("keyword1", keyword1);

        Map<String, Object> keyword2 = new HashMap<String, Object>();
        keyword2.put("value", "花拼账户钱包余额");
        data.put("keyword2", keyword2);

        Map<String, Object> keyword3 = new HashMap<String, Object>();
        keyword3.put("value", "拼购到达截止时间到，未能拼成，支付款项已返还余额，可直接使用");
        data.put("keyword3", keyword3);

        reqMap.put("data", data);

        return reqMap;
    }




}
